<template>
  <el-dialog :title="`${isEdit ? '编辑' : '新增'}账号`" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false" :before-close="closeHandler">
    <div>
      <el-form v-if="dialogVisible" ref="RefForm" :model="formData" label-width="80px" :validate-on-rule-change="false" :rules="formRules" status-icon>
        <el-form-item label="显示名称" prop="name">
          <el-input v-model="formData.name" maxlength="16" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="loginName">
          <el-input v-model="formData.loginName" maxlength="16" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="密码" :prop="isCheck ? 'passwordOne' : 'password'">
          <el-input v-model="formData.password" show-password maxlength="16" @blur="blurHandlerOne"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :prop="isCheck ? 'confirmPasswordOne' : 'confirmPassword'">
          <el-input v-model="formData.confirmPassword" show-password maxlength="16" @blur="blurHandlerTwo"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-radio v-model="formData.isAdmin" :label="true">管理员</el-radio>
          <el-radio v-model="formData.isAdmin" :label="false">普通用户</el-radio>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="formData.isEnable" :label="false">启用</el-radio>
          <el-radio v-model="formData.isEnable" :label="true">禁用</el-radio>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeHandler">取 消</el-button>
      <el-button :loading="loadingSubmit" type="primary" @click="handleSubmitOne">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import dialogEditMixin from '@/mixins/dialogEdit'
  import { eleValidator } from '@/utils/tools'
  import { duplicateCheck } from '@/api/api'
  export default {
    mixins: [dialogEditMixin],
    data() {
      return {
        flag: false,
        isCheck: false,
        formData: {
          name: '',
          confirmPassword: '',
          loginName: '',
          password: '',
          isAdmin: false,
          isEnable: false
        },
        formRules: {
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '名称不能为空' },
                { rule: 'isRepeat', msg: { value: '名称重复', url: '/User/Exists', key: 'name' } }
              ]),
              trigger: 'blur'
            }
          ],
          loginName: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '用户名不能为空' },
                { rule: 'isRepeat', msg: { value: '用户名重复', url: '/User/Exists', key: 'loginName' } },
                { rule: 'isNumberLetterLine', msg: '只能输入数字字母下划线' }
              ]),
              trigger: 'blur'
            }
          ],
          passwordOne: [],
          confirmPasswordOne: [],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            {
              validator: eleValidator([
                {
                  rule: 'isPassword',
                  msg: '最少输入位数10；必须包含数字字母和特殊字符；不可输入汉字或3位连续数字或3位相同数字'
                }
              ]),
              trigger: 'blur'
            }
          ],
          confirmPassword: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(new Error('确认密码不能为空'))
                } else if (value === this.formData.password) {
                  callback()
                } else {
                  if (this.formData.password) {
                    callback(new Error('密码不一致'))
                  } else {
                    callback(new Error('请输入密码再输入确认密码'))
                  }
                }
              },
              trigger: 'blur'
            }
          ]
        },
        timeId: null
      }
    },
    watch: {
      dialogVisible: function (newValue, oldValue) {
        if (newValue) {
          return
        }
        this.$refs.RefForm.clearValidate()
      },
      isEdit: function (newValue, oldValue) {
        if (newValue) {
          this.isCheck = true
        } else {
          this.isCheck = false
        }
      }
    },
    methods: {
      blurHandlerOne() {
        if (!this.isEdit) {
          return
        }
        let val = this.formData.password
        // 匹配不能是中文
        let noChinese = /^[^\u4e00-\u9fa5]{10,}$/
        // 匹配必须包含数字字母和特殊字符
        let patrn = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、])/
        // 匹配三位相同数字
        let two = /(\d)\1{2}/
        // 匹配三位连续数字
        let one = /\d((?<=0)1|(?<=1)2|(?<=2)3|(?<=3)4|(?<=4)5|(?<=5)6|(?<=6)7|(?<=7)8|(?<=8)9){2}/
        if (!noChinese.test(val) || one.test(val) || two.test(val) || !patrn.test(val)) {
          this.$message.error('最少输入位数10；必须包含数字字母和特殊字符；不可输入汉字或3位连续数字或3位相同数字')
        }
      },
      blurHandlerTwo() {
        if (!this.isEdit) {
          return
        }
        let val = this.formData.confirmPassword
        if (!this.formData.password) {
          this.$message.error('请先输入密码，再输入确认密码！')
          return
        }
        if (this.formData.confirmPassword !== this.formData.password) {
          this.$message.error('两次密码输入不一致！')
        }
      },
      handleSubmitOne() {
        if (this.isEdit) {
          if (!this.formData.password && this.formData.confirmPassword) {
            this.$message.error('请输入密码！')
            return
          }
          if (this.formData.password && !this.formData.confirmPassword) {
            this.$message.error('请输入确认密码！')
            return
          }
        }
        this.handleSubmit()
      },
      closeHandler() {
        this.formData = {
          name: '',
          confirmPassword: '',
          loginName: '',
          password: '',
          isAdmin: false,
          isEnable: false
        }
        // 变为添加模式
        this.isEdit = false
        // 关闭模态窗
        this.dialogVisible = false
      },
      resetFormData() {
        this.formData = {
          name: '',
          loginName: '',
          password: '',
          isAdmin: false,
          isEnable: false
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-form-item {
    margin-bottom: 30px;
  }
</style>
